package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ Author xsd
 * @ crate time 2020/5/27 15:14
 * @ 描述 自定义线程池
 * zj: ThreadPoolTaskExecutor 自定义参数_防止oom
 */
@Configuration
public class ExecutorConfig {
    /** Set the ThreadPoolExecutor's core pool size. */
    private static final int CORE_POOL_SIZE = 16;
    /** Set the ThreadPoolExecutor's maximum pool size. */
    private static final int MAX_POOL_SIZE = 100;
    /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */
    private static final int QUEUE_CAPACITY = 32;
    /** Set the life period for the free threads. */
    private static final int AWAIT_TERMINATION_SECONDS = 120;

    @Bean
    public Executor exportAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setThreadNamePrefix("thread pool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(AWAIT_TERMINATION_SECONDS);
        executor.initialize();
        return executor;
    }
}
